//
//  FPluginHostProxy.m
//  Foundation
//
//  Created by 三井 on 2019/10/18.
//

#import "FPluginHostProxy.h"
#import "NSObject+FPlugin.h"

@interface FPluginHostProxy ()

/// 每一个插件对应的主视图副本
@property (nonatomic, strong) NSMutableDictionary<NSString *, FPluginFake *> *mPluginFakeMap;
@property (nonatomic, weak) id source;

@end

@implementation FPluginHostProxy

- (instancetype)init {
    if (self = [super init]) {
        _mPluginFakeMap = [NSMutableDictionary dictionary];
    }
    return self;
}

- (instancetype)initWithSource:(id)source {
    self.source = source;
    return [self init];
}

- (FPluginFake *)prepareArg:(FPluginArg *)arg forPlugin:(id<FPlugin>)plugin {
    FPluginFake *fake = [self shareFakeForIdentifier:[plugin.class identifier]];
    fake.plugin = plugin;
    arg.collectable = (NSObject *)fake;
    return fake;
}

- (FPluginFake *)fakeForData:(FPluginWrappedData *)data {
    for (FPluginFake *fake in self.pluginFakeMap.allValues) {
        if ([fake canHandle:data]) {
            return fake;
        }
    }
    return nil;
}

- (FPluginFake *)shareFakeForIdentifier:(NSString *)identifier {
    FPluginFake * obj = [self.mPluginFakeMap objectForKey:identifier];
    if (!obj) {
        obj = [self fakeForIdentifier:identifier];
        [self.mPluginFakeMap setObject:obj forKey:identifier];
    }
    return obj;
}

- (FPluginFake *)fakeForIdentifier:(NSString *)identifier {
    FPluginFake *fake = [((NSObject *)self.source) fakeForIdentifier:identifier];
    return fake;
}

- (NSDictionary<NSString *,id> *)pluginFakeMap {
    return self.mPluginFakeMap;
}

@end
